const int potPin = 0;          // select the input pin for the potentiometer
int ledPin = 13;               // select the pin for the LED
int ledVal = LOW;
int inputVal = 0;

void setup()
{
  pinMode(ledPin, OUTPUT);     // declare the ledPin as an OUTPUT
  Serial.begin(9600);
}

void loop() {
  int numSamples = 16;
  float floatVal = 0;
  int intVal = 0;
  int fractionVal = 0;
  float fNumSamples = numSamples;
  float sampleSum = 0;
  for(int index = 0; index < numSamples; index++) {
    sampleSum += analogRead(0);      // read the voltage on the pot
    delay(1);
  }
  floatVal = sampleSum / (fNumSamples * 1.0f);
  if(floatVal < 0) floatVal = 0;
  if(floatVal > 128) floatVal = 128;
  intVal = floor(floatVal);
  fractionVal = round((floatVal - intVal) * 128.0);
  // write value of potentiometer
  Serial.write(255);
  Serial.write(intVal);
  Serial.write(fractionVal);
  // check for input
  if(Serial.available() >= 2) {
    if(Serial.read() == 255) {
       inputVal = Serial.read();
       if(inputVal == 0) ledVal = LOW;
       if(inputVal == 1) ledVal = HIGH;
    }
  }
  digitalWrite(ledPin, ledVal);
}

